package com.ruoyi.system.service.impl;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import cn.hutool.core.io.FileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.config.FilePathConfig;
import com.ruoyi.system.utils.ExcelToPdf;
import com.ruoyi.system.utils.NumToChinese;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.TTributeListMapper;
import com.ruoyi.system.domain.TTributeList;
import com.ruoyi.system.service.ITTributeListService;
import com.ruoyi.common.core.text.Convert;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 进贡管理Service业务层处理
 *
 * @author ruoyi
 * @date 2022-04-26
 */
@Service
public class TTributeListServiceImpl implements ITTributeListService {
    @Autowired
    private TTributeListMapper tTributeListMapper;

    @Autowired
    private FilePathConfig filePathConfig;


    private final String XLSX = ".xlsx";

    private final String PDF = ".pdf";


    public static final String[] CN_NUMBERS = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};

    /**
     * 查询进贡管理
     *
     * @param id 进贡管理主键
     * @return 进贡管理
     */
    @Override
    public TTributeList selectTTributeListById(String id) {
        return tTributeListMapper.selectTTributeListById(id);
    }

    /**
     * 查询进贡管理列表
     *
     * @param tTributeList 进贡管理
     * @return 进贡管理
     */
    @Override
    public List<TTributeList> selectTTributeListList(TTributeList tTributeList) {
        return tTributeListMapper.selectTTributeListList(tTributeList);
    }

    /**
     * 新增进贡管理
     *
     * @param tTributeList 进贡管理
     * @return 结果
     */
    @Override
    public int insertTTributeList(TTributeList tTributeList) {
        tTributeList.setId(IdUtils.fastSimpleUUID());
        tTributeList.setCreateTime(DateUtils.getNowDate());
        return tTributeListMapper.insertTTributeList(tTributeList);
    }

    /**
     * 修改进贡管理
     *
     * @param tTributeList 进贡管理
     * @return 结果
     */
    @Override
    public int updateTTributeList(TTributeList tTributeList) {
        return tTributeListMapper.updateTTributeList(tTributeList);
    }

    /**
     * 批量删除进贡管理
     *
     * @param ids 需要删除的进贡管理主键
     * @return 结果
     */
    @Override
    public int deleteTTributeListByIds(String ids) {
        return tTributeListMapper.deleteTTributeListByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除进贡管理信息
     *
     * @param id 进贡管理主键
     * @return 结果
     */
    @Override
    public int deleteTTributeListById(String id) {
        return tTributeListMapper.deleteTTributeListById(id);
    }

    @Override
    public void exportInfo(String id) {

    }

    @Override
    public void exportInfo(String id, HttpServletResponse response, HttpServletRequest request) throws IOException {


        //读取捐赠信息
        TTributeList tTributeList = tTributeListMapper.selectTTributeListById(id);

        String formFileName = tTributeList.getName() + "-感谢状.xlxs";


        //读取模板文件
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("excel/templete.xlsx");

//
//        ExcelWriter excelWriter = EasyExcel.write(out).withTemplate(inputStream).build();
        //构建文件夹
        String tempPath = filePathConfig.getTempPath() + File.separatorChar + tTributeList.getId();
        String xlsxTempPath = tempPath + XLSX;
        String pdfTempPath = tempPath + PDF;

        ExcelWriter excelWriter = EasyExcel.write(xlsxTempPath).withTemplate(inputStream).build();

        Map<String, Object> map = new HashMap<>();
        map.put("name", tTributeList.getName());
        map.put("address", tTributeList.getAddress());

        Long price = tTributeList.getPrice();

        Price price1 = new Price(price);

        //开始解析金钱
        map.put("wan", price1.wan);
        map.put("qian", price1.qian);
        map.put("bai", price1.bai);
        map.put("shi", price1.shi);
        map.put("goods", tTributeList.getGoods());
        NumToChinese.toChinese(price.toString());

        Calendar dateTime = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(tTributeList.getCreateTime());
        UpperDate formatDate = dataToUpper(format);

        //解析日期
        map.put("year", formatDate.year);
        map.put("month", formatDate.month);
        map.put("day", formatDate.day);


//        map.put("name",tTributeList.getName());
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        excelWriter.fill(map, writeSheet);
        excelWriter.finish();

        //开始读取转换pdf文件
        ExcelToPdf.excel2pdf(xlsxTempPath, pdfTempPath);
        //导出
        response.setHeader("Content-disposition",
                String.format("attachment; filename=\"%s\"", formFileName));
        response.setContentType("application/pdf;charset=utf-8");
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream in = FileUtil.getInputStream(new File(pdfTempPath));

        BufferedInputStream fileIn = new BufferedInputStream(new FileInputStream(pdfTempPath));

        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }

        in.close();
        out.close();


    }

    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(new Date());
//        String enddate=dataToUpper(format);
//        System.out.println(enddate);

    }


    class Price {
        String wan;
        String qian;
        String bai;
        String shi;

        public Price(Long price) {
            //百万          十万            万                千            百                十            个              角                分
            String tenThousand = "", thousand = "", hundred = "", ten = "";
            long midVal = (long) (((price + 0.000001) * 100)); //转化成整形
            String valStr = String.valueOf(midVal); //转化成字符串
            //确保字符串长度大于等于2
            if (valStr.length() == 1) {
                valStr = "0" + valStr;
            }
            String head = valStr.substring(0, valStr.length() - 2);//取整数部分
            int headLen = head.length();
            //9000000
            if (headLen < 7) {
                int headLen2 = head.length();
                if (headLen2 < 7) {
                    String added = "";
                    for (int i = 0; i < 7 - headLen2; i++) {
                        added += "a";
                    }
                    head = added + head;
                }
                tenThousand = head.charAt(2) == 'a' ? "" : head.charAt(2) + "";
                thousand = head.charAt(3) == 'a' ? "" : head.charAt(3) + "";
                hundred = head.charAt(4) == 'a' ? "" : head.charAt(4) + "";
                ten = head.charAt(5) == 'a' ? "" : head.charAt(5) + "";
            } else if (headLen == 7) {
                tenThousand = head.charAt(2) + "";
                thousand = head.charAt(3) + "";
                hundred = head.charAt(4) + "";
                ten = head.charAt(5) + "";
            }

            int wan = Integer.parseInt(tenThousand == "" ? "0" : tenThousand);
            int qian = Integer.parseInt(thousand == "" ? "0" : thousand);
            int bai = Integer.parseInt(hundred == "" ? "0" : hundred);
            int shi = Integer.parseInt(ten == "" ? "0" : ten);
            this.wan = CN_NUMBERS[wan];
            this.qian = CN_NUMBERS[qian];
            this.bai = CN_NUMBERS[bai];
            this.shi = CN_NUMBERS[shi];
        }

        /**
         * 进行解析
         *
         * @param price
         */
        public Price tranPrice(Long price) {
            if (price == null) {
                return null;
            }

            return this;
        }
    }


    // 将数字转化为⼤写（字体格式可⾃⼰定义）
    public static String numToUpper(int num) {
//        String u[] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
//        String u[] = {"零","⼀","⼆","三","四","五","六","七","⼋","九"};
        char[] str = String.valueOf(num).toCharArray();
        StringBuilder rstr = new StringBuilder();
        for (char c : str) {
            rstr.append(CN_NUMBERS[Integer.parseInt(c + "")]);
        }
        return rstr.toString();
    }

    // ⽉转化为⼤写
    public static String monthToUppder(int month) {
        if (month < 10) {
            return numToUpper(month);
        } else if (month == 10) {
            return "拾";
        } else {
            return "拾" + numToUpper(month - 10);
        }
    }

    public static String dayToUppder(int day) {
        if (day < 20) {
            return monthToUppder(day);
        } else {
            char[] str = String.valueOf(day).toCharArray();
            if (str[0] == '0') {
                return numToUpper(Integer.parseInt(str[0] + "")) + "拾";
            } else if (str[0] == '2') {
                return "廿" + numToUpper(Integer.parseInt(str[1] + ""));
            } else if (str[0] == '3') {
                return "卅" + numToUpper(Integer.parseInt(str[1] + ""));
            } else {
                return "";
            }
        }
    }

    public UpperDate dataToUpper(String dateString) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date dateTime = null;
        try {
            dateTime = simpleDateFormat.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar ca = Calendar.getInstance();
        ca.setTime(dateTime);
        int year = ca.get(Calendar.YEAR);
        int month = ca.get(Calendar.MONTH) + 1;
        int day = ca.get(Calendar.DAY_OF_MONTH);
        UpperDate upperDate = new UpperDate();
        upperDate.year = numToUpper(year);
        upperDate.month = monthToUppder(month);
        upperDate.day = dayToUppder(day);
        return upperDate;
    }


}

class UpperDate {
    String year;
    String month;
    String day;
}